package com.example.courseapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.adapter.FoodAdapter;
import com.example.courseapp.adapter.SportAdapter;
import com.example.courseapp.bean.ChildDietaryRecords;
import com.example.courseapp.bean.ChildInformation;
import com.example.courseapp.bean.ChildSportRecords;
import com.example.courseapp.bean.FoodBean;
import com.example.courseapp.bean.SportInfo;
import com.example.courseapp.custom.CustomClassifyRecycleViewAdapter;
import com.example.courseapp.custom.CustomRecycleViewAdapter;
import com.example.courseapp.custom.CustomRecycleViewAdapter1;
import com.example.courseapp.net.CourseService;
import com.google.gson.Gson;
import com.kongzue.dialogx.dialogs.BottomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChildInfoActivity extends AppCompatActivity {

    TextView name, age, height, weight, bmi, foodEmpty, sportEmpty,sex,tv_state;

    Button button, addFood, addSport, commitFood, commitSport, searchFood, searchSport, report, fenxi, change_bt, chart;
    CourseService service;

    List<FoodBean> dataArrayList = new ArrayList<>();
    List<SportInfo> dataArrayList1 = new ArrayList<>();

    RecyclerView foodLayout, sportLayout;

    FoodAdapter foodAdapter = new FoodAdapter();
    SportAdapter sportAdapter = new SportAdapter();
    List<FoodBean.ChildrenDTO> foodInfoList = new ArrayList<>();
    List<SportInfo> sportInfoList = new ArrayList<>();

    ChildInformation childInformation;
    Integer childID;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_child_info);
        viewInit();
        getData();
        clickListener();
    }

    private void viewInit() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        change_bt = findViewById(R.id.change_bt);

        button = findViewById(R.id.exit);
        chart = findViewById(R.id.chart);
        fenxi = findViewById(R.id.fenxi);
        childID = getIntent().getIntExtra("childID", 0);


        service = RetrofitHelper.getInstance().createService(CourseService.class);


        name = findViewById(R.id.name);
        sex = findViewById(R.id.sex);
        age = findViewById(R.id.age);
        height = findViewById(R.id.height);
        weight = findViewById(R.id.weight);
        bmi = findViewById(R.id.bmi);
        addFood = findViewById(R.id.addFood);
        addSport = findViewById(R.id.addSport);
        searchSport = findViewById(R.id.searchSport);

        foodLayout = findViewById(R.id.foodLayout);
        sportLayout = findViewById(R.id.sportLayout);
        commitFood = findViewById(R.id.commitFood);
        commitSport = findViewById(R.id.commitSport);
        searchFood = findViewById(R.id.searchFood);
        report = findViewById(R.id.report);
        foodEmpty = findViewById(R.id.foodEmpty);
        sportEmpty = findViewById(R.id.sportEmpty);

        tv_state = findViewById(R.id.state);



        foodLayout.setAdapter(foodAdapter);
        foodLayout.setLayoutManager(new LinearLayoutManager(this));

        sportLayout.setAdapter(sportAdapter);
        sportLayout.setLayoutManager(new LinearLayoutManager(this));
    }

    private void clickListener() {

        button.setOnClickListener(v -> {
            finish();
        });
        change_bt.setOnClickListener(v -> {
            if (childInformation != null) {
                Intent intent = new Intent(this, AddChildActivity.class);
                intent.putExtra("childInfo", childInformation);
                startActivity(intent);
            }
        });
        chart.setOnClickListener(v -> {
            startActivity(new Intent(this, ChartActivity.class).putExtra("childID", childID));
        });
        fenxi.setOnClickListener(v -> {
            startActivity(new Intent(this, RecordActivity2.class).putExtra("childID", childID));
        });

        report.setOnClickListener(v -> {
            startActivity(new Intent(this, ReportActivity.class).putExtra("childID", childID));
        });

        searchFood.setOnClickListener(view -> {
            startActivity(new Intent(this, ChildFoodActivity.class).putExtra("childID", childID));
        });

        searchSport.setOnClickListener(view -> {
            startActivity(new Intent(this, ChildSportActivity.class).putExtra("childID", childID));
        });

        addFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFoodDialog();
            }
        });

        commitFood.setOnClickListener(v -> {

            if (foodInfoList == null || foodInfoList.size() <= 0) {
                Toast.makeText(this, "提交数据不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            ChildDietaryRecords childDietaryRecords = new ChildDietaryRecords();
            childDietaryRecords.setChildInformation(childInformation);
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            childDietaryRecords.setCreateTime(formattedDateTime);
            String str = new Gson().toJson(foodInfoList);
            str = str.replaceAll("foodname", "foodName");

            childDietaryRecords.setFood(str);
            service.saveDietaryRecords(childDietaryRecords).enqueue(new Callback<Boolean>() {
                @Override
                public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                    if (Boolean.TRUE.equals(response.body())) {
                        Toast.makeText(ChildInfoActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                        foodInfoList.clear();
                        foodAdapter.bindData(foodInfoList);
                    }
                }

                @Override
                public void onFailure(Call<Boolean> call, Throwable t) {

                }
            });
        });

        commitSport.setOnClickListener(v -> {

            if (sportInfoList == null || sportInfoList.size() <= 0) {
                Toast.makeText(this, "提交数据不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            ChildSportRecords childDietaryRecords = new ChildSportRecords();
            childDietaryRecords.setChildInformation(childInformation);
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            childDietaryRecords.setCreateTime(formattedDateTime);
            String str = new Gson().toJson(sportInfoList);
            childDietaryRecords.setSport(str);
            service.saveSportRecords(childDietaryRecords).enqueue(new Callback<Boolean>() {
                @Override
                public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                    if (Boolean.TRUE.equals(response.body())) {
                        Toast.makeText(ChildInfoActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                        sportInfoList.clear();
                        sportAdapter.bindData(sportInfoList);
                    }
                }

                @Override
                public void onFailure(Call<Boolean> call, Throwable t) {

                }
            });
        });
        addSport.setOnClickListener(v -> showSportDialog());
    }

    private void getData() {
        service.getFoodList().enqueue(new Callback<List<FoodBean>>() {
            @Override
            public void onResponse(Call<List<FoodBean>> call, @NonNull Response<List<FoodBean>> response) {
                LogUtils.i("dataArrayList === " + GsonUtils.toJson(response.body()));
                List<FoodBean> foodInfoList = response.body();
                if (foodInfoList != null && foodInfoList.size() > 0) {
                    dataArrayList.addAll(foodInfoList);
                }

            }

            @Override
            public void onFailure(Call<List<FoodBean>> call, Throwable t) {

            }
        });


        service.getSportInfo().enqueue(new Callback<List<SportInfo>>() {
            @Override
            public void onResponse(Call<List<SportInfo>> call, @NonNull Response<List<SportInfo>> response) {
                List<SportInfo> sportInfos = response.body();
                dataArrayList1.addAll(sportInfos);
            }

            @Override
            public void onFailure(Call<List<SportInfo>> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        getUserInfo();
    }

    private void getUserInfo() {
        service.getChildById(childID).enqueue(new Callback<ChildInformation>() {
            @Override
            public void onResponse(Call<ChildInformation> call, Response<ChildInformation> response) {
                childInformation = response.body();
                runOnUiThread(() -> {
                    if (childInformation != null) {
                        name.setText("姓名：" + childInformation.getChildName());
                        age.setText("年龄：" + childInformation.getAge());
                        height.setText("身高：" + childInformation.getHeight() + "cm");
                        weight.setText("体重：" + childInformation.getWeight() + "kg");
                        sex.setText("性别：" +childInformation.getSex());
                        bmi.setText("BMI：" + childInformation.getBmi());

                        String bmi = childInformation.getBmi();
                        Double iBmi = Double.valueOf(bmi);
                        String result;

                        if (iBmi < 18.5) {
                            result = "低于正常体重";
                        } else if (iBmi >= 18.5 && iBmi < 25) {
                            result = "正常体重";
                        } else if (iBmi >= 25 && iBmi < 30) {
                            result = "超重";
                        } else if (iBmi >= 30 && iBmi < 35) {
                            result = "一类肥胖";
                        } else if (iBmi >= 35 && iBmi < 40) {
                            result = "二类肥胖";
                        } else {
                            result = "三类肥胖";
                        }

                        tv_state.setText("状态："+ result);
                    }
                });
            }

            @Override
            public void onFailure(Call<ChildInformation> call, Throwable t) {

            }
        });
    }

    public void showFoodDialog() {
        BottomDialog.build().setCustomView(new OnBindView<BottomDialog>(R.layout.layout_custom_recycleview) {
            @Override
            public void onBind(BottomDialog bottomDialog, View view) {

                RecyclerView recyclerView = (RecyclerView) view;
                LinearLayoutManager layoutManager = new LinearLayoutManager(ChildInfoActivity.this);
                recyclerView.setLayoutManager(layoutManager);

                CustomClassifyRecycleViewAdapter adapter = new CustomClassifyRecycleViewAdapter(dataArrayList);

                adapter.setOnItemClickListener((parent, view1, position, id) -> {
                    showChildDialog(dataArrayList.get(position).getChildren());
                });
                recyclerView.setAdapter(adapter);

            }
        }).show();


    }

    private void showChildDialog(List<FoodBean.ChildrenDTO> children) {

        BottomDialog.build().setCustomView(new OnBindView<BottomDialog>(R.layout.layout_custom_recycleview) {
            @Override
            public void onBind(BottomDialog bottomDialog, View view) {
                RecyclerView recyclerView = (RecyclerView) view;

                LinearLayoutManager layoutManager = new LinearLayoutManager(ChildInfoActivity.this);
                recyclerView.setLayoutManager(layoutManager);
                CustomRecycleViewAdapter cadapter = new CustomRecycleViewAdapter(children);

                cadapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        foodInfoList.add(children.get(position));
                        foodAdapter.bindData(foodInfoList);
                        if (foodAdapter.getItemCount() > 0) {
                            foodEmpty.setVisibility(View.GONE);
                        }
                    }
                });
                recyclerView.setAdapter(cadapter);

            }
        }).show();


    }

    public void showSportDialog() {
        BottomDialog.build().setCustomView(new OnBindView<BottomDialog>(R.layout.layout_custom_recycleview) {
            @Override
            public void onBind(BottomDialog bottomDialog, View view) {

                RecyclerView recyclerView = (RecyclerView) view;
                LinearLayoutManager layoutManager = new LinearLayoutManager(ChildInfoActivity.this);
                recyclerView.setLayoutManager(layoutManager);
                CustomRecycleViewAdapter1 adapter = new CustomRecycleViewAdapter1(dataArrayList1);
                adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        sportInfoList.add(dataArrayList1.get(position));
                        sportAdapter.bindData(sportInfoList);
                        if (sportAdapter.getItemCount() > 0) {
                            sportEmpty.setVisibility(View.GONE);
                        }
                    }
                });
                recyclerView.setAdapter(adapter);


            }
        }).show();
    }
}